package com.sakura.thread.chapter2;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * Created by apple on 2018/12/24.
 */
public class TestUnSafe2 {
    static final Unsafe unsafe;
    static final long stateOffset;
    private  volatile long state = 0;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);

            stateOffset = unsafe.objectFieldOffset(TestUnSafe2.class.getDeclaredField("state"));
        } catch (Exception e) {
            e.printStackTrace();
            throw  new Error(e);
        }
    }

    public static void main(String[] args) {
        TestUnSafe2 test = new TestUnSafe2();
        Boolean success = unsafe.compareAndSwapInt(test, stateOffset, 0, 1);
        System.out.println(success);
    }
}
